package com.backend.controller.rbac;

import com.backend.annotation.RequireRole;
import com.backend.service.rbac.UserRoleService;
import com.common.constant.MessageConstant;
import com.common.result.Result;
import com.pojo.dto.AddRoleToUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userRole")
public class UserRoleController {
    @Autowired
    UserRoleService userRoleService;
    /**
     * 删除某个用户的所有角色
     */
    @DeleteMapping("/deleteRolesByUserId/{userId}")
    @RequireRole("admin")
    public Result deleteRolesByUserId(@PathVariable("userId") Long userId) {
        if (userRoleService.deleteRolesByUserId(userId) == 0) {
            return Result.error(MessageConstant.DELETE_ROLES_FAILED);
        }
        return Result.success(MessageConstant.DELETE_ROLES_SUCCESS);
    }
    /**
     *向表中添加某个用户的角色
     */
    @PostMapping("/addRolesToUser")
    @RequireRole("admin")
    public Result addRolesToUser(@RequestBody AddRoleToUserDTO addRoleToUserDTO) {
        Integer result = userRoleService.addRolesToUser(addRoleToUserDTO);
        if (result == 0) {
            return Result.error(MessageConstant.ADD_USER_ROLE_FAIL);
        }
        return Result.success(MessageConstant.ADD_USER_ROLE_SUCCESS);
    }
    /**
     * 通过用户id查询该用户拥有的所有角色
     */
    @GetMapping("/selectRolesByUserId/{userId}")
    @RequireRole("admin")
    public Result getRolesByUserId(@PathVariable("userId") Long userId) {
        List<String> rolesByUserId = userRoleService.getRolesByUserId(userId);
        return Result.success(rolesByUserId);
    }
    /**
     * 修改某个用户所拥有的角色
     */
    @PutMapping("/updateRolesToUser")
    @RequireRole("admin")
    public Result updateRolesToUser(@RequestBody AddRoleToUserDTO addRoleToUserDTO) {
        Integer result = userRoleService.updateRolesToUser(addRoleToUserDTO);
        if (result == 0) {
            return Result.error(MessageConstant.UPDATE_USER_ROLE_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_USER_ROLE_SUCCESS);
    }
}